package com.binvshe.binvshe.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.ListDataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.organization.OrganizationFragment;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.utils.DateTimeUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;

import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/8/25
 */
public class ActivityFragment extends SwipeListFragment {

    private int mPage = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initToolBar();
        startLoading();
        ButterKnife.bind(this, view);
        OrganizationFragment.setPaddingTop(getActivity(), getRootView());
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        mConvenientBanner.startTurning(5000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mConvenientBanner.stopTurning();
    }

    private void initToolBar() {
        showToolbar();
        setTitle("活动购票");
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        getData().clear();
        mPage = 0;
        startLoading();
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new HotActiviesListAdapter(getContext());
    }

    @Override
    public void onStartLoading() {
        getListData();
        getBannerData("activity");
    }

    private ListDataRequestListener<ActivityEntity> mResponceListener = new ListDataRequestListener<>(this, ActivityEntity.class, true);


    View headerView;
    ConvenientBanner mConvenientBanner;

    @Override
    public View createHeaderView(LayoutInflater inflater) {
        headerView = inflater.inflate(R.layout.activies_header, null);
        initHeadView(headerView);
        return headerView;
    }

    private void initHeadView(View view) {
        TextView mTvPastAct = (TextView) view.findViewById(R.id.mTvPastAct);
        TextView mTvNearbyAct = (TextView) view.findViewById(R.id.mTvNearbyAct);
        TextView mTvClassifyAct = (TextView) view.findViewById(R.id.mTvClassifyAct);
        mTvPastAct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyToast.showToast(getContext(), "暂未开放");
            }
        });
        mTvNearbyAct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyToast.showToast(getContext(), "暂未开放");
            }
        });
        mTvClassifyAct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EasyToast.showToast(getContext(), "暂未开放");
            }
        });
        mConvenientBanner = (ConvenientBanner) view.findViewById(R.id.convenientBanner);
    }

    public void getListData() {
        if (mResponceListener.getResponseDataParser().hasMore()) {
            mPage++;
        }
        MyHttpRequest request = new MyHttpRequest(getContext());
        UrlParams urlParams = new UrlParams();
        urlParams.put(ParamKey.PAGE, mPage + "");
        urlParams.put(ParamKey.SIZE, 8 + "");
        request.get(UrlCenter.ACTIVIES, urlParams, mResponceListener);
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long itemId) {
        super.onItemClick(arg0, arg1, position, itemId);
        ActivityEntity entity = (ActivityEntity) getData().get(position);
        DetailActivity.start(getContext(), entity.getId(), entity.getIcon(), entity.getName());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    //设置banner数据
    private void setBannerData(final List<BannerEntity> bannerData) {
        mConvenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, bannerData).setPageIndicator(new int[]{R.mipmap.icon_nav_n, R.mipmap.icon_nav_p})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        mConvenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String[]  strs=bannerData.get(position).getLink().split("id=");
                int id = Integer.parseInt(strs[1]);
                bannerData.get(position).getLink().startsWith("id=");
                if(bannerData.get(position).getLink().startsWith("event://")){
                    DetailActivity.start(getContext(),id, bannerData.get(position).getImage(), bannerData.get(position).getName());
                }else if(bannerData.get(position).getLink().startsWith("http://")){
                    WebView webView = new WebView(getActivity());
                    webView.getSettings().setDomStorageEnabled(true);
                    webView.getSettings().setDatabaseEnabled(true);
                    webView.getSettings().setJavaScriptEnabled(true);
                    webView.loadUrl(bannerData.get(position).getLink());
                }else{

                }
            }
        });

    }

    /**
     * 获取banner数据
     */
    private void getBannerData(String type) {
        MyHttpRequest request = new MyHttpRequest(getContext());
        String url = String.format(UrlCenter.BANNER_TYPE, type);
        request.get(url, null, new DataRequestListener<List<BannerEntity>>(BannerEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(List<BannerEntity> bannerEntity) {
                super.onSuccess(bannerEntity);
                setBannerData(bannerEntity);

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    public class HotActiviesListAdapter extends RecyclerViewBaseAdapter<ActivityEntity> {

        public HotActiviesListAdapter(Context con) {
            super(con);

        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.item_hot_activies));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final VH viewHolder = (VH) holder;
            final ActivityEntity activityEntity = getData().get(position);
            if (!TextUtils.isEmpty(activityEntity.getIcon()))
                IML.load(getContext(), viewHolder.mImgHead, activityEntity.getIcon());
            if (!TextUtils.isEmpty(activityEntity.getName()))
                viewHolder.mTvTitle.setText(activityEntity.getName());

            String beginTime = DateTimeUtil.getDateStr(new Date(activityEntity.getBegin_time()));
            String endTime = DateTimeUtil.getDateStr(new Date(activityEntity.getEnd_time()));

            viewHolder.mTvDate.setText(beginTime + "  -  " + endTime);
            viewHolder.mTvActPlace.setText(activityEntity.getAddress());
            if (!TextUtils.isEmpty(activityEntity.getPrice()))
                viewHolder.mTvTicketPrice.setText("￥"+activityEntity.getPrice());

            viewHolder.mTvActNumber.setText("剩余票数:"+activityEntity.getTicket_stock() + "张");
        }

        public class VH extends RecyclerView.ViewHolder {

            @Bind(R.id.mImgHead)
            ImageView mImgHead;
            @Bind(R.id.mTvTitle)
            TextView mTvTitle;
            @Bind(R.id.mTvDate)
            TextView mTvDate;
            @Bind(R.id.mTvActNumber)
            TextView mTvActNumber;
            @Bind(R.id.mTvTicketPrice)
            TextView mTvTicketPrice;
            @Bind(R.id.tvActPlace)
            TextView mTvActPlace;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
